<template>
  <div>
    <a-card>
      <a-row :gutter="20">
        <a-col :span="6">
          <a-input-search
            v-model="queryParam.title"
            placeholder="输入文章名查找"
            enter-button
            allowClear
            @search="getArticleList"
          />
        </a-col>
        <a-col :span="4">
          <a-button
            type="primary"
            @click="$router.push({ name: 'addArticle', params: { id: 0 } })"
            >新增</a-button
          >
        </a-col>
        <a-col :span="6" :offset="4">
          <a-select
            defaultValue="请选择分类"
            style="width: 200px"
            @change="cateChange"
          >
            <a-select-option
              v-for="category in categoryList"
              :key="category.id"
              :value="category.id"
              >{{ category.name }}</a-select-option
            >
          </a-select>
        </a-col>
      </a-row>
      <a-table
        :rowKey="(record) => record.ID"
        :columns="columns"
        :pagination="paginationOption"
        :dataSource="ArticleList"
        bordered
      >
        <span slot="img" class="article-img" slot-scope="img">
          <img :src="img" alt="" />
        </span>
        <template slot="action" slot-scope="data">
          <div class="actionSlot">
            <a-button
              type="primary"
              icon="edit"
              style="margin-right: 15px"
              @click="
                $router.push({ name: 'addArticle', params: { id: data.ID } })
              "
              >编辑</a-button
            >
            <a-button
              type="danger"
              icon="delete"
              style="margin-right: 15px"
              @click="deleteArticle(data.ID)"
              >删除</a-button
            >
          </div>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      ArticleList: [],
      categoryList: [],
      selectedCate: 0,
      columns: [
        {
          title: "ID",
          dataIndex: "ID",
          width: "5%",
          key: "id",
          align: "center",
        },
        {
          title: "分类",
          dataIndex: "category.name",
          width: "10%",
          key: "name",
          align: "center",
        },
        {
          title: "标题",
          dataIndex: "title",
          width: "10%",
          key: "title",
          align: "center",
        },
        {
          title: "描述",
          dataIndex: "desc",
          width: "20%",
          key: "desc",
          align: "center",
        },
        {
          title: "缩略图",
          dataIndex: "img",
          width: "20%",
          key: "img",
          align: "center",
          scopedSlots: { customRender: "img" },
        },
        {
          title: "操作",
          width: "15%",
          key: "action",
          scopedSlots: { customRender: "action" },
          align: "center",
        },
      ],
      paginationOption: {
        pageSizeOptions: ["2", "5", "10", "15"],
        defaultCurrent: 1,
        defaultPageSize: 2,
        total: 0,
        showSizeChanger: true,
        showTotal: (total) => `共${total}条`,
        onChange: (current, pageSize) => {
          this.paginationOption.defaultCurrent = current;
          // 判断是否有选中分类选项
          if (this.selectedCate > 0) {
            // 有选中
            this.getArticleOnCategory(this.selectedCate);
          } else {
            this.getArticleList();
          }
        },
        onShowSizeChange: (current, size) => {
          this.paginationOption.defaultCurrent = 1;
          this.paginationOption.defaultPageSize = size;
          // 判断是否有选中分类选项
          if (this.selectedCate > 0) {
            // 有选中
            this.getArticleOnCategory(this.selectedCate);
          } else {
            this.getArticleList();
          }
        },
      },
      queryParam: {
        title: "",
        pageSize: 2,
        pageNum: 1,
      },
    };
  },
  created() {
    this.getArticleList();
    this.getCategoryList();
  },
  methods: {
    // 获取分类
    async getCategoryList() {
      const { data: res } = await this.$http.get("/categories");
      if (res.status != 200) return this.$message.error("获取分类信息失败");
      this.categoryList = res.data;
    },
    // 分页获取文章信息
    async getArticleList() {
      let that = this;
      const { data: res } = await this.$http.get("/articles", {
        params: {
          title: that.queryParam.title,
          pageNum: that.paginationOption.defaultCurrent,
          pageSize: that.paginationOption.defaultPageSize,
        },
      });

      if (res.status != 200) return this.$message.error(res.msg);
      this.ArticleList = res.data;
      this.paginationOption.total = res.total;
    },
    // 删除文章
    deleteArticle(id) {
      let that = this;
      this.$confirm({
        title: "确定要删除该文章吗?",
        content: "一旦删除无法恢复",
        okText: "Yes",
        okType: "danger",
        cancelText: "No",
        async onOk() {
          const { data: res } = await that.$http.delete(`/article/${id}`);
          if (res.status != 200) return that.$message.error(res.msg);
          that.$message.success("删除成功");
          that.getArticleList();
        },
        onCancel() {
          that.$message.info("已取消");
        },
      });
    },
    // 选择分类
    async cateChange(value) {
      // 更新选择的分类
      this.selectedCate = Number.parseInt(value);
      // 查询分类下的文章并更新表格中文章的内容
      this.getArticleOnCategory(this.selectedCate);
    },
    // 查询某个分类下的所有文章
    async getArticleOnCategory(id) {
      const { data: res } = await this.$http.get(`/articles/${id}`, {
        params: {
          pageNum: this.paginationOption.defaultCurrent,
          pageSize: this.paginationOption.defaultPageSize,
        },
      });
      if (res.status != 200) return this.$message.error("文章查询失败");
      this.ArticleList = res.data;
      this.paginationOption.total = res.total;
    },
  },
};
</script>

<style lang="scss" scoped>
.actionSlot {
  display: flex;
  justify-content: center;
}
.article-img {
  width: 100%;
  height: 100%;
  img {
    width: 100px;
    height: 80px;
  }
}
</style>